package com.changgou.oauth.util;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

//创建令牌，给拦截器携带   默认配置的管理员和oauth放行
public class AdminToken {
    public static String adminToken(){
        //获取私钥
        ClassPathResource resource = new ClassPathResource("changgou.jks");
        //读取证书数据
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource,"changgou".toCharArray());

        //获取证书中的一对密钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("changgou", "changgou".toCharArray());
        //获取私钥  ->RSA算法
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        //添加令牌的载荷，需要私钥加盐【RSA算法】
        Map<String, Object> map = new HashMap<>();
        map.put("nikename","tomcat");
        map.put("adress","sz");
        //给管理员校色
        map.put("authorities",new String[] {"admin","oauth"});

        Jwt jwt = JwtHelper.encode(JSON.toJSONString(map), new RsaSigner(privateKey));
        String token = jwt.getEncoded();
        return token;

    }
}
